package com.webserver.controller;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;
import com.webserver.vo.Article;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ArticleController {
    public static final String USER_DIR = "./articles/";

    static {
        File dir = new File(USER_DIR);
        if(!dir.exists()){ //如果该目录不存在则自动创建
            dir.mkdir();
        }
    }

    /**
     * 处理发表文章操作
     * @param request
     * @param response
     */
    public void writeArticle(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理发表文章...");

        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");
        System.out.println(title+","+author+","+content);

        if(title==null||author==null||content==null){
            File file = new File("./webapps/myweb/article_fail.html");
            response.setEntity(file);
        }

        Article article = new Article(title,author,content);
        try (
                FileOutputStream fos = new FileOutputStream(USER_DIR+title+".obj");
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                ){
            oos.writeObject(article);
            File file = new File("./webapps/myweb/article_success.html");
            response.setEntity(file);
        }catch (IOException e){
            e.printStackTrace();
        }
        System.out.println("发表文章完毕！");
    }
}
